package com.allen.retrofit2_rxjava2.view.selectImage.adapter;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.allen.retrofit2_rxjava2.R;
import com.allen.retrofit2_rxjava2.view.selectImage.entity.ChooseUploadParam;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.engine.bitmap_recycle.BitmapPool;
import com.bumptech.glide.load.resource.bitmap.BitmapTransformation;
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions;
import com.bumptech.glide.request.RequestOptions;

import java.io.IOException;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * Created by lierdong on 2016/11/29.
 */
public class FeedbackImageAdapter extends RecyclerView.Adapter<FeedbackImageAdapter.BaseViewHolder> {

    private static final String TAG = "FeedbackImageAdapter";

    public static final int TYPE_ADD = 0;
    public static final int TYPE_TEXT = 1;
    public static final int TYPE_IMG = 2;

    private Context context;
    private ArrayList<ChooseUploadParam> params;


    public void updateListView(ArrayList<ChooseUploadParam> list) {
        this.params = list;
        notifyDataSetChanged();
    }

    public FeedbackImageAdapter(Context context, ArrayList<ChooseUploadParam> params) {
        this.context = context;
        this.params = params;
    }

    public ArrayList<ChooseUploadParam> getParams() {
        return params;
    }

    @Override
    public BaseViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View itemView;
        BaseViewHolder holder = null;
        switch (viewType) {
            case TYPE_ADD://添加
                itemView = View.inflate(context, R.layout.item_add, null);
                holder = new AddItemViewHolder(itemView);
                break;

            case TYPE_IMG:
                itemView = View.inflate(context, R.layout.item_img, null);
                holder = new ImgItemViewHolder(itemView);
                break;

        }
        return holder;
    }

    @Override
    public void onBindViewHolder(BaseViewHolder holder, int position) {
        ChooseUploadParam param = params.get(position);
        int viewType = getItemViewType(position);
        switch (viewType) {

            case TYPE_IMG:
                ImgItemViewHolder imgItemViewHolder = (ImgItemViewHolder) holder;
                String imgPath = param.getPath();
                int degreee = readBitmapDegree(imgPath);
                if (degreee == 0) {
                    try {
                        Glide.with(context.getApplicationContext())
                                .load(imgPath)
                                .apply(new RequestOptions()
                                        .diskCacheStrategy(DiskCacheStrategy.NONE)
                                        .skipMemoryCache(true)
                                        .error(R.mipmap.banner_default)
                                        .transform(new RotateTransformation(context)))
                                .transition(DrawableTransitionOptions.withCrossFade())
                                .into(imgItemViewHolder.iv_img);
                        Log.i("0度", "000000000000");

                    } catch (Exception e) {
                    }
                }
                if (degreee == 270) {
                    try {
                        Glide.with(context.getApplicationContext()).load(imgPath)
                                .apply(new RequestOptions()
                                        .diskCacheStrategy(DiskCacheStrategy.NONE)
                                        .skipMemoryCache(true)
                                        .error(R.mipmap.banner_default)
                                        .transform(new RotateTransformation(context)))
                                .into(imgItemViewHolder.iv_img);
                        Log.i("0度", "90909090909090");
                    } catch (Exception e) {
                    }
                }


                break;
        }
    }

    // 读取图像的旋转度
    private int readBitmapDegree(String path) {
        int degree = 0;
        try {
            ExifInterface exifInterface = new ExifInterface(path);
            int orientation = exifInterface.getAttributeInt(
                    ExifInterface.TAG_ORIENTATION,
                    ExifInterface.ORIENTATION_NORMAL);
            switch (orientation) {
                case ExifInterface.ORIENTATION_ROTATE_90:
                    degree = 90;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_180:
                    degree = 180;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_270:
                    degree = 270;
                    break;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return degree;
    }


    public class RotateTransformation extends BitmapTransformation {
        private float rotateRotationAngle = 0f;

        public RotateTransformation(Context context) {
//            super(context);
//            this.context = context;
////            this.rotateRotationAngle = rotateRotationAngle;
        }

        @Override
        protected Bitmap transform(BitmapPool pool, Bitmap toTransform, int outWidth, int outHeight) {
            Matrix matrix = new Matrix();
            matrix.postRotate(rotateRotationAngle);
            return Bitmap.createBitmap(toTransform, 0, 0, toTransform.getWidth(), toTransform.getHeight(), matrix, true);
        }

        public String getId() {
            return "rotate" + rotateRotationAngle;
        }

        @Override
        public void updateDiskCacheKey(MessageDigest messageDigest) {

        }
    }

    @Override
    public int getItemCount() {
        return params.size();
    }

    @Override
    public int getItemViewType(int position) {
        return params.get(position).getType();
    }


    class BaseViewHolder extends RecyclerView.ViewHolder {

        public View itemView;

        public BaseViewHolder(View itemView) {
            super(itemView);
            this.itemView = itemView;
        }
    }

    class AddItemViewHolder extends BaseViewHolder {

        public AddItemViewHolder(View itemView) {
            super(itemView);
            itemView.setOnClickListener(new MyItemClickListener(TYPE_ADD, this));
        }
    }

    //图片长安监听
    class ImgItemViewHolder extends BaseViewHolder implements View.OnClickListener {

        public ImageView iv_img;
        public ImageView image_delete;

        public ImgItemViewHolder(View itemView) {
            super(itemView);
            itemView.setOnClickListener(new MyItemClickListener(TYPE_IMG, this));
            iv_img = (ImageView) itemView.findViewById(R.id.iv_img);
            image_delete = (ImageView) itemView.findViewById(R.id.image_delete);
            image_delete.setOnClickListener(this);
        }

        @Override
        public void onClick(View view) {
            Log.d("onClick :", "" + getLayoutPosition());
            if (getLayoutPosition() >= 0) { //重复点击 可能在删除时产生-1
                int position = getLayoutPosition();
                if (ondeleteItemClickListener != null && position >= 0) {
                    ondeleteItemClickListener.ondeleteItemClick(position);
                }
                removeItem(getLayoutPosition());
            }
        }
    }

    private OnItemClickListener onItemClickListener;

    public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
        this.onItemClickListener = onItemClickListener;
    }

    public interface OnItemClickListener {
        void onItemClick(int position, int viewType, ChooseUploadParam param);
    }

    class MyItemClickListener implements View.OnClickListener {

        private BaseViewHolder holder;
        private int viewType;

        public MyItemClickListener(int viewType, BaseViewHolder holder) {
            this.viewType = viewType;
            this.holder = holder;
        }

        @Override
        public void onClick(View v) {
            int position = holder.getLayoutPosition();
            if (onItemClickListener != null && position >= 0) {
                onItemClickListener.onItemClick(position, viewType, params.get(position));
            }
        }

    }

    private void removeItem(int position) {
        Log.d("removeItem", "" + params.size());
        params.remove(position);
        if (params.get(getItemCount() - 1).getType() != TYPE_ADD) {
            ChooseUploadParam param = new ChooseUploadParam();
            param.setType(TYPE_ADD);
            params.add(param);
        }
        notifyItemRemoved(position);
    }

    public void addItem(ChooseUploadParam param) {
        switch (param.getType()) {

            case TYPE_IMG:
                int position = getItemCount() - 1;
                if (getItemCount() >= 3) {
                    params.set(position, param);
                    notifyItemChanged(position);
                } else {
                    params.add(position, param);
                    notifyItemInserted(position);
                }
                break;
        }
    }

    public void addItems(List<ChooseUploadParam> params) {
        for (ChooseUploadParam param : params) {
            String mPath = param.getPath();
            int degreee = readBitmapDegree(mPath);
            addItem(param);
        }
    }

    public int getImgCount() {
        int count = 0;
        for (ChooseUploadParam param : params) {
            if (param.getType() == TYPE_IMG) {
                count++;
            }
        }
        return count;
    }

    /**
     * 删除图片的监听
     */
    private OndeleteItemClickListener ondeleteItemClickListener;

    public void setOndeleteItemClickListener(OndeleteItemClickListener ondeleteItemClickListener) {
        this.ondeleteItemClickListener = ondeleteItemClickListener;
    }

    public interface OndeleteItemClickListener {
        void ondeleteItemClick(int position);
    }
}
